/**
 * \* Created with IntelliJ IDEA.
 * \* User: Administrator
 * \* Date: 2022/3/25
 * \* Time: 17:40
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * \
 */

class Counter{
    //这个变量就是两个线程要去自增的变量
    volatile public int count;

    synchronized public void increase(){
        synchronized (this){
            count++;
        }
    }
    public static void func(){
        synchronized(Counter.class){

        }
    }
}

public class Demo15 {

    private static Counter counter = new Counter();
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(()->{
            for (int i = 0; i < 50000; i++) {
                counter.increase();
            }
        });
        Thread t2 = new Thread(()->{
            for (int i = 0; i < 50000; i++) {
                counter.increase();
            }
        });
        t1.start();
        t2.start();

        //必须在t1和t2都执行完了之后，再打印count的结果
        //否则，main和t1、t2之间都是并发的关系，这会导致t1、t2还没执行完就先执行下面的打印操作
        t1.join();
        t2.join();

        //在main中打印一下两个线程之后，得到count结果
        System.out.println(counter.count);
    }
}
